<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="json2.js"></script>
<script>

function escape_quote(s)
{
	return s.replace(/'/g,"\\'");
}

function metaweb_query(query,callback)
{
	query_envelope = {'query' : query};
 	service_url = 'http://api.freebase.com/api/service/mqlread';
	url = service_url  + '?callback=?&query=' + encodeURIComponent(JSON.stringify(query_envelope));
	$.getJSON(url,function(res) {callback(res.result)})
}

function create_tile(name,img)
{
	if(img.length>0)
	{
		img = img[0].id
		imgtag='<img width="200px" src="http://img.freebase.com/api/trans/raw'+img+'" />\n';
	}
	else imgtag="";
	return '<div class="tile" onclick="search(\''+escape_quote(name)+'\')">'+name+"<br />"+imgtag+"</div>\n";
}
function filmactors(name,callback)
{
query = [{
  "type": "/film/film",
  "name": name,
  "starring": [{
    "actor": {
      "name": null,
      "/common/topic/image": [{
        "id":       null,
        "optional": true,
        "limit":    3
      }]
    }
  }]
}];
	metaweb_query(query,function(res){
		if(res.length>0)
		{
			actors = res[0].starring;
			var text ="";
			for(i in actors){
				name = actors[i].actor.name;
				img = actors[i].actor["/common/topic/image"];
				text += create_tile(name,img);
			}
			$("#content").html(text);
		}
		else
		{
			$("#content").html("Not found :(");
			callback(name);
		}
	});
}

function actorfilms(name,callback)
{
query = [{
  "type": "/film/film",
  "name": null,
  "/common/topic/image": [{
  "id":       null,
  "optional": true,
  "limit":    3
  }],
  "starring": [{
    "actor": {
      "name": name
    }
  }]
}];
	metaweb_query(query,function(res){
		if(res.length>0)
		{
			var text ="";
			for(i in res){
				name = res[i].name;
				img = res[i]["/common/topic/image"];
				text += create_tile(name,img);
			}
			$("#content").html(text);
			return true;
		}
		else
		{
			$("#content").html("Not found :(");
			return false;
		}
	});
};

function search(query)
{
	if(query)
	{
		name = query;
		$("#query").val(query);
	}
	else
		name = $("#query").val();
	$("#content").html('Searching for "'+name+'"...');
	filmactors(name,function (n) {actorfilms(n,null)});
}
</script>
<style>
.tile {
	float:left;
	max-width:220px;
	margin:3;
	padding:3;
	background-color:white;
	color:black;
	text-align:center;
}
div.tile:hover {
	background-color:blue;
}
body {
	background-color:black;
	color:white;
}
#footer {
position: fixed;
bottom: 0;
background-color:black;
}
</style>
</head>
<body>
Search for some film: <input type="text" id="query" value="Armageddon" onkeypress="if(event.keyCode==13) search();"/><button onclick="search();">Go!</button>
<div id="content">
Ready.
</div>
<div id="footer">
By <a href="http://bunyk.wordpress.com/">Bunyk T.</a>, 2011.
Source: <a href="http://www.freebase.com/">Freebase</a>, licensed under <a href="http://creativecommons.org/licenses/by/2.5/">CC-BY</a>. 
</div>
</body>
</html>
